package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.wephone.Student.R;
import com.wephone.Student.bean.ZhidaoAskInfoResponse;
import com.wephone.Student.bean.data.ZhidaoAskData;
import com.wephone.Student.bean.data.ZhidaoCommentData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.RoundImageView;
import com.wephone.Student.util.ShareReferenceUtil;

public class ZhidaoAnswerListActivity extends BaseActivity {
	private ListView listView;
	private ListViewAdapter adapter;
	private ZhidaoAskData askData;
	private List<ZhidaoCommentData> results = new ArrayList<ZhidaoCommentData>();
	private int listItemIdx;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoAnswerListActivity.this,ZhidaoAskInfoResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					ZhidaoAskInfoResponse res = (ZhidaoAskInfoResponse)response;
					
					if(res.getData().getList()==null || adapter.pageIdx>=res.getData().getList().size() || res.getData().getList().size()<Constants.PAGE_SIZE){
						adapter.hasMore = false;
					}else{
						adapter.pageIdx++;
					}
					if(res.getData().getList()!=null){
						results.addAll(res.getData().getList());
						adapter.notifyDataSetChanged();
					}
				}
			}
		};
		return handler;
	}
	
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoAnswerListActivity.this,ZhidaoAskInfoResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					Toast.makeText(getApplicationContext(), "问题举报成功", Toast.LENGTH_SHORT).show();
				}
			}
		};
		return handler;
	}
	
	private MyResponseHandler getHandler3(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoAnswerListActivity.this,ZhidaoAskInfoResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					results.clear();
					adapter.hasMore = true;
					adapter.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("id", askData.getId());
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_GET_ZHIDAO_ASK_INFO_URL, params, getHandler());
				}
			}
		};
		return handler;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1 && resultCode==11){
			results.clear();
			adapter.hasMore = true;
			adapter.pageIdx = 1;
			adapter.notifyDataSetChanged();
			
			RequestParams params = new RequestParams();
			params.put("id", askData.getId());
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			HttpClient.getInstance().get(Constants.API_GET_ZHIDAO_ASK_INFO_URL, params, getHandler());
		}else if(requestCode==2 && resultCode==22){
			results.clear();
			adapter.hasMore = true;
			adapter.pageIdx = 1;
			adapter.notifyDataSetChanged();
			
			RequestParams params = new RequestParams();
			params.put("id", askData.getId());
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			HttpClient.getInstance().get(Constants.API_GET_ZHIDAO_ASK_INFO_URL, params, getHandler());
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhi_dao_answer_list);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			askData = (ZhidaoAskData)bundle.getSerializable("askData");
			
			init();
		}
	}
	
	private void init(){
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("askData", askData);
				bundle.putSerializable("commentData", results.get(arg2));
				startActivityForResult(new Intent(getApplicationContext(),ZhidaoAnswerDetailActivity.class).putExtras(bundle),2);
			}});
//		listView.setOnItemLongClickListener(new ListView.OnItemLongClickListener(){
//			@Override
//			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//				// TODO Auto-generated method stub
//				listItemIdx = arg2;
//				if(results.get(listItemIdx).getuInfo().getuId().equals(BaseActivity.getMyInfo(getApplicationContext()).getuId())){
//					new AlertDialog.Builder(ZhidaoAnswerListActivity.this).setTitle("提示")
//					.setItems(new String[]{"删除问题"}, new DialogInterface.OnClickListener(){
//						@Override
//						public void onClick(DialogInterface arg0, int arg1) {
//							if(arg1==0){
//								RequestParams params = new RequestParams();
//								params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
//								params.put("id", askData.getId());
//								HttpClient.getInstance().get(Constants.API_ZHIDAO_DEL_ASK_URL, params, getHandler3());
//							}
//						}})
//					.setNegativeButton("取消", null).show();
//					return true;
//				}
//				return false;
//			}});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.add_answer_layout).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Bundle bundle = new Bundle();
				bundle.putString("askId", askData.getId());
				startActivityForResult(new Intent(getApplicationContext(),ZhidaoAddAnswerActivity.class).putExtras(bundle),1);
			}
		});
		
		findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showShareDialog();
			}
		});
		
		((TextView)findViewById(R.id.top_title_text)).setText(askData.getCommentCount()+"个回答");
		((TextView)findViewById(R.id.item_title_text)).setText(askData.getTitle());
		((TextView)findViewById(R.id.item_content)).setText(askData.getContent());
		((TextView)findViewById(R.id.item_view_number)).setText(askData.getViewnum());
		((TextView)findViewById(R.id.item_message_number)).setText(askData.getCommentCount());
		
		RoundImageView itemImage = (RoundImageView)findViewById(R.id.question_ask_image);
		if(!TextUtils.isEmpty(askData.getuInfo().getuIcon())){
			DisplayImageOptions options = new DisplayImageOptions.Builder()
	        .showStubImage(R.drawable.default_user_logo)
	        .showImageOnFail(R.drawable.default_user_logo)
	        .bitmapConfig(Bitmap.Config.ARGB_8888)
	        .cacheInMemory()
	        .cacheOnDisc()
//	        .displayer(new RoundedBitmapDisplayer(1000))
	        .build();
			String endStr = askData.getuInfo().getuIcon().substring(askData.getuInfo().getuIcon().lastIndexOf("."));
			imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
			
			itemImage.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("userData", askData.getuInfo());
					startActivity(new Intent(getApplicationContext(),UserInfoDetailActivity.class).putExtras(bundle));
				}
			});
		}else{
			itemImage.setImageResource(R.drawable.default_user_logo);
		}
		
		if(askData.getPictures()==null || askData.getPictures().length<=0){
			findViewById(R.id.zhidao_pic_layout).setVisibility(View.GONE);
		}else{
			if(askData.getPictures().length>0){
				if(TextUtils.isEmpty(askData.getPictures()[0])){
					findViewById(R.id.zhidao_detail_pic_image_1).setVisibility(View.GONE);
				}else{
					DisplayImageOptions options = new DisplayImageOptions.Builder()
			        .showStubImage(R.drawable.default_image)
			        .showImageOnFail(R.drawable.default_image)
			        .bitmapConfig(Bitmap.Config.ARGB_8888)
			        .cacheInMemory()
			        .cacheOnDisc()
			        .displayer(new RoundedBitmapDisplayer(0))
			        .build();
					imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[0], (ImageView)findViewById(R.id.zhidao_detail_pic_image_1), options);
					
					findViewById(R.id.zhidao_detail_pic_image_1).setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View arg0) {
							String bigImgUrl = Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[0]; 
							startActivity(new Intent(getApplicationContext(),GalleryUrlActivity.class).putExtra("imgUrl", bigImgUrl));
						}
					});
				}
			}
			if(askData.getPictures().length>1){
				DisplayImageOptions options = new DisplayImageOptions.Builder()
		        .showStubImage(R.drawable.default_image)
		        .showImageOnFail(R.drawable.default_image)
		        .bitmapConfig(Bitmap.Config.ARGB_8888)
		        .cacheInMemory()
		        .cacheOnDisc()
		        .displayer(new RoundedBitmapDisplayer(0))
		        .build();
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[1], (ImageView)findViewById(R.id.zhidao_detail_pic_image_2), options);
				
				findViewById(R.id.zhidao_detail_pic_image_2).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						String bigImgUrl = Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[1]; 
						startActivity(new Intent(getApplicationContext(),GalleryUrlActivity.class).putExtra("imgUrl", bigImgUrl));
					}
				});
			}else{
				findViewById(R.id.zhidao_detail_pic_image_2).setVisibility(View.GONE);
			}
			if(askData.getPictures().length>2){
				DisplayImageOptions options = new DisplayImageOptions.Builder()
		        .showStubImage(R.drawable.default_image)
		        .showImageOnFail(R.drawable.default_image)
		        .bitmapConfig(Bitmap.Config.ARGB_8888)
		        .cacheInMemory()
		        .cacheOnDisc()
		        .displayer(new RoundedBitmapDisplayer(0))
		        .build();
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[2], (ImageView)findViewById(R.id.zhidao_detail_pic_image_3), options);
				
				findViewById(R.id.zhidao_detail_pic_image_3).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						String bigImgUrl = Constants.IMAGE_PHOTO_SERVER_PATH+askData.getPictures()[2]; 
						startActivity(new Intent(getApplicationContext(),GalleryUrlActivity.class).putExtra("imgUrl", bigImgUrl));
					}
				});
			}else{
				findViewById(R.id.zhidao_detail_pic_image_3).setVisibility(View.GONE);
			}
		}
		RequestParams params = new RequestParams();
		params.put("id", askData.getId());
		params.put("Page", "1");
		params.put("PageSize", ""+Constants.PAGE_SIZE);
		HttpClient.getInstance().get(Constants.API_GET_ZHIDAO_ASK_INFO_URL, params, getHandler());
	}
	
	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_zhi_dao_answer_list_item, null);
			}
			ZhidaoCommentData commData = results.get(position);
			TextView itemName = (TextView)convertView.findViewById(R.id.item_answer_name);
			RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.item_image);
			if(commData.getAnonymous()!=null && commData.getAnonymous().equals("1")){
				itemImage.setImageResource(R.drawable.default_user_logo);
				itemName.setText("匿名");
			}else{
				itemName.setText(commData.getuInfo().getuName());
				if(!TextUtils.isEmpty(commData.getuInfo().getuIcon())){
					DisplayImageOptions options = new DisplayImageOptions.Builder()
			        .showStubImage(R.drawable.default_user_logo)
			        .showImageOnFail(R.drawable.default_user_logo)
			        .bitmapConfig(Bitmap.Config.ARGB_8888)
			        .cacheInMemory()
			        .cacheOnDisc()
//			        .displayer(new RoundedBitmapDisplayer(1000))
			        .build();
					String endStr = commData.getuInfo().getuIcon().substring(commData.getuInfo().getuIcon().lastIndexOf("."));
					imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+commData.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
				}else{
					itemImage.setImageResource(R.drawable.default_user_logo);
				}
			}
			TextView itemTime = (TextView)convertView.findViewById(R.id.item_answer_time);
			itemTime.setText(sdf.format(new Date(Long.parseLong(commData.getCtime())*1000)));
			TextView itemContent = (TextView)convertView.findViewById(R.id.item_answer_content);
			itemContent.setText(commData.getContent());
			TextView zanNumText = (TextView)convertView.findViewById(R.id.item_num_text);
			zanNumText.setText(commData.getThankNum());
			//load more
			if(position>=results.size()-1 && hasMore){
				RequestParams params = new RequestParams();
				params.put("id", askData.getId());
				params.put("Page", ""+pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_GET_ZHIDAO_ASK_INFO_URL, params, getHandler());
			}
			return convertView;
		}		
	}

	private PopupWindow popupWindow;
	
	private void showShareDialog(){
		View popupView = getLayoutInflater().inflate(R.layout.dialog_zhidao_share_view, null);
		popupWindow = new PopupWindow(popupView,getWindowManager().getDefaultDisplay().getWidth(),getWindowManager().getDefaultDisplay().getHeight());
		popupView.findViewById(R.id.zhidao_share_edit_text_1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popupWindow.dismiss();
				
				Intent intent = new Intent(Intent.ACTION_SEND);  
				intent.setType("text/plain");  
				intent.putExtra(Intent.EXTRA_SUBJECT, askData.getTitle());  
				intent.putExtra(Intent.EXTRA_TEXT, askData.getContent());  
				startActivity(Intent.createChooser(intent, "分享问题")); 

			}
		});
		if(ShareReferenceUtil.getIsNiming(getApplicationContext())){
			((TextView)popupView.findViewById(R.id.zhidao_share_edit_text_2)).setText("撤销匿名");
		}
		popupView.findViewById(R.id.zhidao_share_edit_text_2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popupWindow.dismiss();
				
				if(ShareReferenceUtil.getIsNiming(getApplicationContext())){
					ShareReferenceUtil.saveIsNiming(getApplicationContext(), false);
					((TextView)arg0.findViewById(R.id.zhidao_share_edit_text_2)).setText("启用匿名");
					Toast.makeText(getApplicationContext(), "匿名已撤销", Toast.LENGTH_SHORT).show();
				}else{
					ShareReferenceUtil.saveIsNiming(getApplicationContext(), true);
					((TextView)arg0.findViewById(R.id.zhidao_share_edit_text_2)).setText("撤销匿名");
					Toast.makeText(getApplicationContext(), "匿名已启用", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		popupView.findViewById(R.id.zhidao_share_edit_text_3).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popupWindow.dismiss();
				new AlertDialog.Builder(ZhidaoAnswerListActivity.this).setTitle("举报问题")
				.setItems(R.array.zhidao_report_questions_array, new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if(arg1==0){
							RequestParams params = new RequestParams();
							params.put("id", askData.getId());
							params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
							params.put("report", "1");
							HttpClient.getInstance().get(Constants.API_DO_ZHIDAO_ASK_REPLY_REPORT_URL, params, getHandler2());
						}else if(arg1==1){
							RequestParams params = new RequestParams();
							params.put("id", askData.getId());
							params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
							params.put("report", "2");
							HttpClient.getInstance().get(Constants.API_DO_ZHIDAO_ASK_REPLY_REPORT_URL, params, getHandler2());
						}else if(arg1==2){
							RequestParams params = new RequestParams();
							params.put("id", askData.getId());
							params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
							params.put("report", "3");
							HttpClient.getInstance().get(Constants.API_DO_ZHIDAO_ASK_REPLY_REPORT_URL, params, getHandler2());
						}
					}})
				.setNegativeButton("取消", null).show();
			}
		});
		popupView.findViewById(R.id.btn_cancel_share).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popupWindow.dismiss();
			}
		});
		popupWindow.update();
		popupWindow.setFocusable(true);
		popupWindow.setTouchable(true); 
		popupWindow.showAtLocation(findViewById(R.id.main_top_layout), Gravity.CENTER, 0, 0);
	}
	
}
